package top.zy.service.zymallgoodsservice.spec.service;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.zy.common.zymallcommon.utils.constants.CacheConstants;
import top.zy.common.zymallcommon.utils.exception.ZymalException;
import top.zy.service.zymallgoodsinterface.entity.SpecGroup;
import top.zy.service.zymallgoodsinterface.entity.SpecParam;
import top.zy.service.zymallgoodsinterface.entity.Specification;
import top.zy.service.zymallgoodsinterface.vo.SpecGroupVo;
import top.zy.service.zymallgoodsservice.spec.dao.SpecGroupMapper;
import top.zy.service.zymallgoodsservice.spec.dao.SpecParamMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 10:43 2019/6/24
 */
@Service
public class SpecServiceImpl implements SpecService {

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper specParamMapper;

    @Cacheable(value = CacheConstants.CACHE_GOODS_SPEC_CATEGORYID,key = "#p0")
    @Override
    public List<SpecGroup> querySpecGroupByCategoryId(Long categoryId) {
        return specGroupMapper.querySpecGroupByCategoryId(categoryId);
    }
    @Override
    public List<SpecParam> queryParams(Long gid, Long cid,  Boolean searching) {
        return specParamMapper.SelectParams(gid,cid,searching);
    }

    @Cacheable(value = CacheConstants.CACHE_GOODS_SPEC_PARAM_CATEGORYID,key = "#p0")
    @Override
    public List<SpecGroupVo> querySpecGroupAndParamByCid(Long categoryId) {
        List<SpecGroupVo> specGroupVoList=new ArrayList<>();
        List<SpecGroup> specGroupList = specGroupMapper.querySpecGroupByCategoryId(categoryId);
        if (CollectionUtils.isEmpty(specGroupList)){
            throw new ZymalException("规格组查询失败");
        }
        List<SpecParam> specParamList=specParamMapper.SelectParams(null,categoryId,null);
        Map<Long,List<SpecParam>> param=new HashMap<>();
        for (SpecParam specParam : specParamList) {
            if (!param.containsKey(specParam.getGroupId())){
                param.put(specParam.getGroupId(),new ArrayList<>());
            }
            param.get(specParam.getGroupId()).add(specParam);
        }
        for (SpecGroup specGroup : specGroupList) {
          SpecGroupVo specGroupVo=new SpecGroupVo();
            BeanUtils.copyProperties(specGroup,specGroupVo);
            specGroupVo.setParams(param.get(specGroupVo.getId()));
            specGroupVoList.add(specGroupVo);
        }
        return specGroupVoList;
    }
}
